import {
	computed,
	watch,
	nextTick
} from 'vue';
import {
	useStore
} from 'vuex';
import createApi from '../api/commonAPI.js';
import {
	REQUEST_SUCCESS
} from '../utils/config.js';

const LOGIN_TIMESTAMP_KEY = 'login_timestamp'; // 定义一个常量作为本地存储的键

export function useAuth() {
	const store = useStore();
	const commonAPI = createApi(store);
	
	// 创建计算属性来封装 Vuex 状态
	const token = computed(() => store.state.auth.token);
	const session_key = computed(() => store.state.auth.session_key);
	const hasAuth = computed(() => store.state.auth.hasAuth);
	const userInfo = computed(() => store.state.auth.userInfo);
	const user_id = computed(() => store.state.auth.user_id);
	const account = computed(() => store.state.auth.account);
	const hasSigned = computed(() => store.state.auth.hasSigned);
	const appid = computed(() => store.state.common.appid);
	const notLogin = computed(() => store.state.auth.notLogin);
	
	// 封装 Vuex mutations 的方法
	const SET_NOT_LOGIN = (notLogin) => {
		store.commit('auth/SET_NOT_LOGIN', notLogin);
	};
	const SET_SESSION_KEY = (sessionKey) => {
		store.commit('auth/SET_SESSION_KEY', sessionKey);
	};
	const SET_LOGIN_DATA = (user_id,token,userInfo) => {
		store.commit('auth/SET_LOGIN_DATA',{user_id,token,userInfo});
	};
	const SET_USER_INFO = (userInfo) => {
		store.commit('auth/SET_USER_INFO',{userInfo});
	};
	const SET_USER_ACCOUNT = (account) => {
		store.commit('auth/SET_USER_ACCOUNT',{account});
	};
	const SET_TOKEN = (token) => {
		store.commit('auth/SET_TOKEN', token);
	};
	const SET_AUTH = (auth) => {
		store.commit('auth/SET_AUTH', auth);
	};
	const SET_SIGN = (hasSigned) => {
		store.commit('auth/SET_SIGN', hasSigned);
	};
	const REMOVE_TOKEN = () => {
		store.commit('auth/REMOVE_TOKEN');
	};
	const SET_APPID = (appid) => {
		store.commit('common/SET_APPID', appid);
	};
	
	// watch(() => userInfo.value, (newVal) => {
	// 	if (newVal && newVal.avatar && newVal.nick_name) {
	// 		nextTick(() => {
	// 			SET_AUTH(true);
	// 		});
	// 	} else {
	// 		nextTick(() => {
	// 			SET_AUTH(false);
	// 		});
	// 	}
	// }, { deep: true });
	
	const autoLogin = async (code,appid,inviter_id) => {
		return new Promise((resolve, reject) => {
			try {
				REMOVE_TOKEN()
				commonAPI.autoLogin({
					code,
					appid,
					inviter_id
				}).then((res) => {
					let data = res.data
					if (res.code === REQUEST_SUCCESS) {
						let resToken=data.token
						if(resToken){
							SET_TOKEN(resToken)
							const currentTimestamp = Date.now();
							uni.setStorageSync(LOGIN_TIMESTAMP_KEY, currentTimestamp);
							uni.hideLoading()
							uni.showToast({
								title: '登录成功',
								icon: 'success'
							})
						}
						resolve(data)
					}else{
						reject(res.msg)
					}
					
				})
			} catch (error) {
				reject(res)
			}
		});
	};

	const checkLoginStatus = async (code, appid,inviter_id) => {
		const loginTimestamp = uni.getStorageSync(LOGIN_TIMESTAMP_KEY);
		const savedToken = uni.getStorageSync('token'); 
		const now = Date.now();
		const twentyFourHours = 24 * 60 * 60 * 1000;

		if (!savedToken || !loginTimestamp || (now - loginTimestamp) > twentyFourHours) {
			// console.log('Token 不存在或已过期，执行重新登录');
			uni.showLoading({
				title: '登录中...',
				mask: true
			});
			return autoLogin(code, appid,inviter_id);
		} else {
			// console.log('Token 未过期，直接使用已保存的 Token');
			SET_TOKEN(savedToken);
			return Promise.resolve();
		}
	};
	
	// 新增：整合后的登录方法
	const login = async (inviter_id) => {
		try {
			const appId = await refreshAppId();
			const code = await new Promise(resolve => {
				wx.login({
					success: (loginRes) => {
						resolve(loginRes.code);
					}
				});
			});
			await checkLoginStatus(code, appId,inviter_id);
			await wxGetUserInfo(); // 登录成功后获取用户信息
			SET_NOT_LOGIN(false)
		} catch (e) {
			// console.error('登录流程失败', e);
			// 登录失败后，清除可能存在的过期 token
			SET_NOT_LOGIN(true)
			REMOVE_TOKEN();
			throw e; // 抛出错误，让页面可以捕获
		}
	};
	
	const getUserAccount= async()=>{
		return new Promise((resolve, reject) => {
			try {
				commonAPI.userAccount().then((res) => {
					let data = res.data
					if (res.code === REQUEST_SUCCESS) {
						let user_id=data.id
						if(user_id!=''){
							SET_USER_ACCOUNT(data)
							nextTick(() => {
								resolve(data)
							})
						}else{
							reject(res)
						}
					}else{
						reject(res)
					}
				})
			} catch (error) {
				reject(res)
			}
		});
	}
	const wxGetUserInfo= async(code,session_key,type)=>{
		return new Promise((resolve, reject) => {
			try {
				commonAPI.currentUser().then((res) => {
					if (res.code === REQUEST_SUCCESS) {
						let user_id=res.data.id
						if(user_id!=''){
							SET_USER_INFO(res.data.current)
							// if(res.data.current.avatar===null && res.data.current.nick_name===null && type==='join'){
							// 	uni.navigateTo({
							// 		url:'/pages/userCenter/userInfo'
							// 	})
							// }
							nextTick(() => {
								resolve(res.data)
							})
						}else{
							console.info('REMOVE_TOKEN')
							REMOVE_TOKEN()
							reject(res)
						}
					}else{
						reject(res)
					}
				})
			} catch (error) {
				reject(res)
			}
		});
	}
	const refreshAppId= async(code,session_key)=>{
		return new Promise((resolve, reject) => {
			try {
				const accountInfo =wx.getAccountInfoSync()
				SET_APPID(accountInfo.miniProgram.appId)
				console.log(accountInfo.miniProgram.appId)
				resolve(accountInfo.miniProgram.appId)
				
			} catch (error) {
				reject(res)
			}
		});
	}
	
	return {
		session_key,
		token,
		hasAuth,
		userInfo,
		user_id,
		account,
		REMOVE_TOKEN,
		SET_AUTH,
		SET_USER_INFO,
		SET_USER_ACCOUNT,
		SET_SIGN,
		SET_NOT_LOGIN,
		autoLogin,
		checkLoginStatus,
		wxGetUserInfo,
		getUserAccount,
		refreshAppId,
		login, // 暴露新的登录方法
		hasSigned,
		notLogin
	};
}